package com.prawn.search.service;

import com.prawn.search.dao.DiagnoseDao;
import com.prawn.search.pojo.Diagnose;

import org.elasticsearch.index.query.QueryBuilders;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DiagnoseService {
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    @Autowired
    private DiagnoseDao diagnoseDao;

    /**
     * 模糊查询
     *
     * @param key
     * @return
     */
    public Page<Diagnose> findByKey(String key,int page,int size) {
        String status = "1";
        Pageable pageable = PageRequest.of(page-1,size);
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.boolQuery()
                        .must(QueryBuilders.termQuery("status", status))
                        .must(QueryBuilders.multiMatchQuery(key, "diseaseName", "symptom")))
                .withPageable(pageable)
                .build();

        return elasticsearchTemplate.queryForPage(searchQuery, Diagnose.class);
    }

    /**
     * 查询全部
     *
     * @return
     */
    public Page<Diagnose> findAll(int page, int size) {
        Pageable pageable = PageRequest.of(page-1,size);
        return diagnoseDao.findAll(pageable);
    }

    /**
     * 精准查询
     *
     * @param key
     * @return
     */
    public Page<Diagnose> accurateQuery(String key,int page,int size) {
        String status = "1";
        Pageable pageable = PageRequest.of(page-1,size);
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.boolQuery()
                        .should(QueryBuilders.termQuery("symptom", key))
                        .should(QueryBuilders.termQuery("diseaseName", key))
                        .must(QueryBuilders.termQuery("status", status))
                ).withPageable(pageable)
                .build();

        return elasticsearchTemplate.queryForPage(searchQuery, Diagnose.class);
    }
}
